export function timeFix () {
  const time = new Date()
  const hour = time.getHours()
  return hour < 9 ? '早上好' : hour <= 11 ? '上午好' : hour <= 13 ? '中午好' : hour < 20 ? '下午好' : '晚上好'
}

export function welcome () {
  const arr = ['休息一会儿吧', '准备吃什么呢?', '要不要打一把 LOL', '我猜你可能累了']
  const index = Math.floor(Math.random() * arr.length)
  return arr[index]
}

/**
 * 触发 window.resize
 */
export function triggerWindowResizeEvent () {
  const event = document.createEvent('HTMLEvents')
  event.initEvent('resize', true, true)
  event.eventType = 'message'
  window.dispatchEvent(event)
}

export function handleScrollHeader (callback) {
  let timer = 0

  let beforeScrollTop = window.pageYOffset
  callback = callback || function () {}
  window.addEventListener(
    'scroll',
    event => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        let direction = 'up'
        const afterScrollTop = window.pageYOffset
        const delta = afterScrollTop - beforeScrollTop
        if (delta === 0) {
          return false
        }
        direction = delta > 0 ? 'down' : 'up'
        callback(direction)
        beforeScrollTop = afterScrollTop
      }, 50)
    },
    false
  )
}

export function isIE () {
  const bw = window.navigator.userAgent
  const compare = (s) => bw.indexOf(s) >= 0
  const ie11 = (() => 'ActiveXObject' in window)()
  return compare('MSIE') || ie11
}

/**
 * Remove loading animate
 * @param id parent element id or class
 * @param timeout
 */
export function removeLoadingAnimate (id = '', timeout = 1500) {
  if (id === '') {
    return
  }
  setTimeout(() => {
    document.body.removeChild(document.getElementById(id))
  }, timeout)
}
export function scorePassword (pass) {
  let score = 0
  if (!pass) {
    return score
  }
  // award every unique letter until 5 repetitions
  const letters = {}
  for (let i = 0; i < pass.length; i++) {
      letters[pass[i]] = (letters[pass[i]] || 0) + 1
      score += 5.0 / letters[pass[i]]
  }

  // bonus points for mixing it up
  const variations = {
      digits: /\d/.test(pass),
      lower: /[a-z]/.test(pass),
      upper: /[A-Z]/.test(pass),
      nonWords: /\W/.test(pass)
  }

  let variationCount = 0
  for (var check in variations) {
      variationCount += (variations[check] === true) ? 1 : 0
  }
  score += (variationCount - 1) * 10

  return parseInt(score)
}

export function getBase64(file) {
  return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
  });
}

export function fileProcess(fileUrl){
  return new Promise((resolve,reject)=>{
    var image = new Image();
    // 允许跨域操作
    image.setAttribute("crossOrigin",'anonymous');
    // 给img加上随机值一部分情况下能解决跨域
    image.src = fileUrl + '?time=' + new Date().valueOf();
    // image.src = fileUrl;
    image.onload = function(){
      var base64 = getBase64Image(image);
      console.log(base64,'base64')
      var newFile = dataURLtoFile(base64,'img111');
      console.log(newFile)
      demoImg.src=base64.dataURL;
      var blob = convertBase64UrlToBlob(base64);
      resolve(blob);
    }
    image.onerror = error => reject(error);
  })
}

function getBase64Image(img) {
  var demoCanvas = document.getElementById("demoCanvas");
  demoCanvas.width = img.width;
  demoCanvas.height = img.height;
  var ctx = demoCanvas.getContext("2d");
  ctx.drawImage(img, 0, 0, 300, 150);
  var ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase();
  var dataURL = demoCanvas.toDataURL("image/"+ext);
  return {
    dataURL: dataURL,
    type: "image/"+ext
  };
}

export const isEmail = (email) => {
  var emailRegExp=/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
  if(email == '' || !email) return false;
  return emailRegExp.test(email);
} 

export const timeDiff = (createTime,endTime) =>{
  var diffTimeStr = ''; // 耗时
  var startTime = new Date(createTime).getTime();
  var endTimes = new Date(endTime).getTime();
  if(endTimes > startTime){
    var diffTime = (endTimes - startTime) / 1000;
    if(diffTime < 60){
      diffTimeStr = `${diffTime}秒`
    }else if(diffTime < 3600){
      diffTimeStr = `${parseInt(diffTime / 60)}分${diffTime % 60}秒`
    }else if(diffTime < 3600 * 24){
      diffTimeStr = `${parseInt(diffTime / 3600)}时${parseInt((diffTime % 3600) / 60)}分${((diffTime % 3600)) % 60}秒`
    }else{
      diffTimeStr = `${parseInt(diffTime / 3600 / 24)}天${parseInt((diffTime % (3600 * 24)) / 3600)}时${parseInt(((diffTime % (3600 * 24)) % 3600) / 60)}分${((diffTime % (3600 * 24)) % 3600) % 60}秒`
    }
  }
  return diffTimeStr
}